package org.example.controller;


import io.grpc.stub.StreamObserver;
import net.devh.boot.grpc.client.inject.GrpcClient;
import org.example.stubs.HelloWorldRequest;
import org.example.stubs.HelloWorldResponse;
import org.example.stubs.HelloWorldServiceGrpc;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

import java.util.stream.Stream;

@Component
public class HelloWorldClient {


    @GrpcClient("hello")
    HelloWorldServiceGrpc.HelloWorldServiceStub stub;

    @EventListener(ContextRefreshedEvent.class)
    void sendRequests() {

        final StreamObserver<HelloWorldResponse> responseObserver = new StreamObserver<HelloWorldResponse>() {
            @Override
            public void onNext(HelloWorldResponse helloWorldResponse) {
                System.out.println(helloWorldResponse.getGreeting());
            }

            @Override
            public void onError(Throwable throwable) {
                throwable.printStackTrace();
            }

            @Override
            public void onCompleted() {

            }
        };

        final StreamObserver<HelloWorldRequest> request = stub.sayHello(responseObserver);

        Stream.of("Tom", "Jua")
                .map(HelloWorldRequest.newBuilder()::setName)
                .map(HelloWorldRequest.Builder::build)
                .forEach(request::onNext);

        request.onCompleted();

        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }
}
